require(quantmod)
require(colorRamps)

#get currency data from the FED FRED data series
getSymbols("DEXKOUS",src="FRED") #load Korea
getSymbols("DEXMAUS",src="FRED") #load Malaysia
getSymbols("DEXSIUS",src="FRED") #load Singapore
getSymbols("DEXTAUS",src="FRED") #load Taiwan
getSymbols("DEXCHUS",src="FRED") #load China
getSymbols("DEXJPUS",src="FRED") #load Japan
getSymbols("DEXTHUS",src="FRED") #load Thailand
getSymbols("DEXBZUS",src="FRED") #load Brazil
getSymbols("DEXMXUS",src="FRED") #load Mexico
getSymbols("DEXINUS",src="FRED") #load India
getSymbols("DGS10",src="FRED") #load US 10y yield

currencies<-merge(DEXKOUS,DEXMAUS,DEXSIUS,DEXTAUS,
                  DEXCHUS,DEXJPUS,DEXTHUS,DEXBZUS,DEXMXUS,DEXINUS)
colnames(currencies)<-c("Korea","Malaysia","Singapore","Taiwan",
                        "China","Japan","Thailand","Brazil","Mexico","India")
currencies<-na.omit(currencies)
currencies.roc<-currencies/lag(currencies)-1
currencies.roc[1,]<-0

US10y.roc <- diff(DGS10, lag=1)
US10y.roc[1,] <- 0

curr.10y <- na.omit(merge(currencies.roc,US10y.roc))
#chart.Correlation(curr.10y)

#get rolling correlation of currencies versus the US 10y yield
corr <- as.xts(apply(curr.10y[,1:10],MARGIN=2,FUN=runCor,y=curr.10y[,11],n=500),
               order.by=index(curr.10y))

#order correlations by their ending value
corr <- corr[, order(t(last(corr)),decreasing=TRUE)]

#thanks Joshua Ulrich for showing me how to do this
#stuff we reuse
labs=colnames(corr)
colors=ygobb(15)[3:12]

#make plot
layout(matrix(1:2, 2),heights=c(8,5))
par(mar=c(2,4,4,5),oma=c(2,1,2,0))
plot.zoo(corr,col=colors,lwd=2,screens=1,xlab=NA,ylab="Rolling Correlation",las=1)
#this is the primary change Joshua Ulrich made
#to allow a much nicer labelling of points on a right vertical margin
axis(4, coredata(last(corr)),labels=FALSE)
mtext(labs, 4, at=coredata(last(corr)), col=colors,las=1,line=1,cex=0.5)
title(main="Foreign Currencies to US10y Yield
Rolling 500 day (2-year) Correlation",cex.main=1.25,
adj=0,outer=TRUE,line=-2)
par(mar=c(4,4,2,4))
barplot(last(corr),las=1,beside=TRUE,col=colors,names.arg=labs, ylab=NA,ylim=c(-0.5,0.5),cex.names=0.7,border="gray70")
title(main="Latest 500-day (2-year) Correlation", cex.main=0.8,adj=0)
